/* eslint-disable react/destructuring-assignment */
/* eslint-disable no-underscore-dangle */
/* eslint-disable no-console */
import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import qs from 'qs';
import download from '@/utils/download';
import { exportQAHistories } from '@/services/download';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Card,
  Form,
  Row,
  Col,
  Button,
  Select,
  DatePicker,
  Table,
  Icon,
  Spin,
  Input,
  Tooltip,
  Radio,
  Drawer,
  message
} from 'antd'
import EditQa from '../../KnowledgeManagement/Overview/editQa';
import Tables from '../../../modules/Table';
import Tableb from './Table';
import dataTime from '../../../utils/dataTime';
import styles from './index.less';
import bi from '@/assets/icons/bi.png'
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';
const Option = Select.Option;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const Search = Input.Search;
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1131883_9z1s7xrc0o7.js', // 在 iconfont.cn 上生成
});
const columns1 = [
  {
    title: '知识库分类',
    dataIndex: 'category',
  },
  {
    title: '命中次数',
    dataIndex: 'hitCount',
    sorter: (a, b) => { // 排序

    },
  },
  {
    title: '已解决次数',
    dataIndex: 'resolvedCount',
    sorter: (a, b) => { // 排序

    },
  },
  {
    title: '未解决次数',
    dataIndex: 'unresolvedCount',
    sorter: (a, b) => { // 排序

    },
  },
]

@connect(({ AnswerDetailStatis, loading }) => ({
  AnswerDetailStatis,
  loading: loading.effects['AnswerDetailStatis/fetch'],
}))
class Answer extends Component {
  constructor() {
    super();
    this.state = {
      login: false,
      showModel4: false,
      robotId: '5b2075fc3b000080008e282a',
      sortBy: '',
      type: null,
      from: '',
      to: '',
      page: 1,
      limit: 10,
      search: '',
      type: 0,
      numberA: '0',
      limitA: 10,
      text: '',
      total2: '',
      total1: '',
      nodeId: '',
      nodeIdName: '所有分类',
      close: false,
      qaId: "",
      isUpdate: false,
      sort: 'desc',
      order: 'hitCount',
      switchPd: 'a',
      questions: [],
      searchText: '请输入知识库分类名'
    };
  }



  // eslint-disable-next-line react/sort-comp
  componentDidMount() {
    this.setState({
      login: true
    })
    this.detailCategoryList()
  }

  // 渲染页面前调用一次
  // eslint-disable-next-line react/sort-comp
  componentWillMount() {
    let sysTime = dataTime.formatDate(new Date().getTime()); // 初始时间
    let toTime = moment().subtract('days', 7).format('YYYY/MM/DD');; // 初始时间
    this.setState({
      beginTime: toTime.replace(/\//g, '-'),
      overTime: sysTime.replace(/\//g, '-'),
      from: toTime.replace(/\//g, '-'),
      to: sysTime.replace(/\//g, '-'),
    });

  }

  // 动态获取mock数据
  detailCategoryList = () => {
    this.setState({
      login: true
    })
    const { dispatch, currentUser } = this.props;
    const { sort, from, to, page, limit, search, order } = this.state
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'AnswerDetailStatis/detailCategoryList',
        payload: { sort, from, to, page, limit, search, order },
        callback: res => {

          if (res.list) {
            this.setState({
              login: false
            })
          }
          res.list.map((item, index) => {
            item['key'] = index
          })
          let listMap = res.list

          // eslint-disable-next-line default-case
          this.setState({
            dataSource: listMap,
            total1: res.total,
            login: false
          })
        },
      });
    });

  }

  detailDetailList = () => {  // 问答详细统计--详细统计
    this.setState({
      login: true
    })
    const { dispatch, currentUser } = this.props;
    const { sort, from, to, page, limit, search, order } = this.state
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'AnswerDetailStatis/detailDetailList',
        payload: { sort, from, to, page, limit, search, order },
        callback: res => {

          if (res.list) {
            this.setState({
              login: false
            })
          }
          res.list.map((item, index) => {
            item['key'] = index
          })
          let listMap = res.list

          // eslint-disable-next-line default-case
          this.setState({
            dataSource: listMap,
            total1: res.total,
            login: false
          })
        },
      });
    });

  }

  // 查看
  handleSubmit = () => {
    const { beginTime, overTime } = this.state
    // let userInfo = this.props.form.getFieldsValue();// 获取数据
    // let usercz = this.props.form.resetFields();// 重置表单数据
    //
    if (beginTime && overTime) {
      if (this.state.switchPd === 'a') {
        this.setState({
          from: this.state.beginTime,
          to: this.state.overTime,
        }, () => {
          this.detailCategoryList()
        })
      }
      if (this.state.switchPd === 'b') {
        this.setState({
          from: this.state.beginTime,
          to: this.state.overTime,
        }, () => {
          this.detailDetailList()
        })
      }
    } else {
      message.error('请输入开始至结束日期')
    }

  }

  handleDelete = (item) => {

    this.setState({
      qaId: item.id,
      questions: Array(item.question),
      close: true,
    })
  }

  // 日期选择｛开始日期——结束日期｝
  onChange = (date, dateString) => {
    this.setState({
      beginTime: dateString[0].replace(/\//g, '-'),
      overTime: dateString[1].replace(/\//g, '-'),
      page: 1
    });


  };


  // 新增按钮
  newlyIncreased = () => {
  }

  // 单选框
  onChangeRadio = (e) => {
    this.setState({
      search: '',
      switchPd: e.target.value
    })


    if (e.target.value === 'a') {
      this.props.form.setFields({ "businessName": "" })
      this.setState({ // 分类统计
        type: 0,
        page: 1,
        limit: 10,
        text: '',
        search: '',
        dataSource: [],
        searchText: '请输入知识库分类名'
      }, () => {
        this.detailCategoryList()
      })

    } else if (e.target.value === 'b') {
      this.props.form.setFields({ "businessName": "" })
      this.setState({ // 详细统计
        type: 1,
        page: 1,
        limit: 10,
        text: '',
        search: '',
        dataSource: [],
        searchText: '请输入知识点'
      }, () => {
        this.detailDetailList()
      })

    }
  }

  //
  tables = () => {
    const columns2 = [
      {
        title: '知识点',
        dataIndex: 'question',

      },
      {
        title: '分类',
        dataIndex: 'category',

      },
      {
        title: '命中次数',
        dataIndex: 'hitCount',
        sorter: (a, b) => { // 排序

        },
      },
      {
        title: '已解决次数',
        dataIndex: 'resolvedCount',
        sorter: (a, b) => { // 排序

        },
      },
      {
        title: '未解决次数',
        dataIndex: 'unresolvedCount',
        sorter: (a, b) => { // 排序

        },
      },
      {
        title: '操作',
        render: (text, item) => {
          return (
            <div className={styles.buttongl} onClick={(text) => { this.handleDelete(item) }}><img style={{ marginRight: 5 }} src={bi} />编辑</div>
          )

        },
      }
    ]
    if (this.state.type === 0) {

      return (
        // />
        <div className='zdyTable'>
          <Table

            style={{ padding: '0px 20px 0px 20px' }}
            //  bordered
            columns={columns1}
            dataSource={this.state.dataSource}//数据
            onChange={this.handleChange}
            pagination={{  // 分页
              total: this.state.total1, // 数据总数量
              pageSize: this.state.limit,  // 显示几条一页
              current: this.state.page, // 默认显示几条一页
              showSizeChanger: true,  // 是否显示可以设置几条一页的选项
              showQuickJumper: true,
              onChange: this.onChangeA,
              onShowSizeChange: this.onShowSizeChangeA
            }}
          />
        </div>
      )
    } if (this.state.type === 1) {
      return (
        <Table
          className='zdyTable'
          style={{ padding: '0px 30px 0px 30px' }}
          //  bordered
          columns={columns2}
          dataSource={this.state.dataSource}// 数据
          onChange={this.handleChangeA}
          pagination={{  // 分页
            total: this.state.total1, // 数据总数量
            pageSize: this.state.limit,  // 显示几条一页
            current: this.state.page, // 默认显示几条一页
            showSizeChanger: true,  // 是否显示可以设置几条一页的选项
            showQuickJumper: true,
            onChange: this.onChangeB,
            onShowSizeChange: this.onShowSizeChangeB
          }}
        />
      )
    }
  }

  render() {
    const { getFieldDecorator } = this.props.form


    return (
      <div className={styles.overall}>
        <PageHeaderWrapper>
          <div className={styles.overall}>
            <Row className={styles.colorBackground}>
              <Col style={{ paddingLeft: 18, paddingTop: 6 }} xs={24} span={3} sm={24} md={24} lg={6} xl={4}>
                <div className={styles.buttonAB}>
                  <span className={styles.AccessTrend} />
                  {/* <span>问答记录</span> */}
                  <span style={{ fontSize: 16, color: '#4B5475', borderLeft: "5px solid #13c2f3", paddingLeft: 10, fontWeight: 600 }}>
                    <FormattedMessage id="app.answerDetail.title" defaultMessage="title" />
                  </span>
                  <span style={{ marginLeft: 12 }}>
                    <Tooltip
                      placement="top"
                      title={<FormattedMessage
                        id="app.answerDetail.hint"
                      />}
                      arrowPointAtCenter
                    >
                      <Icon type="info-circle" />
                    </Tooltip>
                  </span>
                </div>
              </Col>
              <Col span={9} xs={0} sm={0} md={0} lg={0} xl={4} />
              <Col span={12} xs={24} sm={24} md={24} lg={18} xl={16} className={styles.zsy}>
                <Form className={styles.buttonA} layout="inline">
                  <FormItem>
                    <RangePicker
                      onChange={this.onChange}
                      style={{ width: 220 }}
                      defaultValue={[
                        moment(this.state.beginTime, dateFormat),
                        moment(this.state.overTime, dateFormat),
                      ]}
                      format={dateFormat}
                    />
                  </FormItem>

                  <FormItem className='buttonYs'>
                    <Button onClick={this.handleSubmit} icon="check">
                      {/* 查看 */}
                      <FormattedMessage id="app.answerDetail.examine" defaultMessage="Examine" />
                    </Button>
                  </FormItem>

                  <FormItem className='buttonYs'>
                    <Button onClick={this.export} icon="arrow-down">
                      {/* 下载 */}
                      <FormattedMessage id="app.answerDetail.derive" defaultMessage="Download" />
                    </Button>
                  </FormItem>
                </Form>
              </Col>
            </Row>
            <Row style={{ background: '#ffffff', paddingTop: 20 }}>
              <Col style={{ height: 52 }} span={24}>
                <span className='radioYs'>
                  <RadioGroup onChange={this.onChangeRadio} defaultValue="a" style={{ marginLeft: 30 }}>
                    <RadioButton value="a"> <FormattedMessage id="app.answerDetail.classified-statistic" defaultMessage="Classified statistic" /></RadioButton>
                    <RadioButton value="b"><FormattedMessage id="app.answerDetail.detail-statistics" defaultMessage="Detail Statistics" /></RadioButton>
                  </RadioGroup>
                </span>

                <Form layout="horizontal" style={{ width: 320, float: 'right', marginRight: 30 }}>

                  <FormItem >
                    {getFieldDecorator('businessName', {
                      initialValue: '',
                    })(
                      <Search
                        placeholder={this.state.searchText}
                        onSearch={value => {
                          if (this.state.switchPd === 'a') {
                            this.setState({
                              search: value,
                              page: 1
                            }, () => {
                              this.detailCategoryList()
                            })
                          }
                          if (this.state.switchPd === 'b') {
                            this.setState({
                              search: value,
                              page: 1
                            }, () => {
                              this.detailDetailList()
                            })
                          }

                        }}
                      />
                    )}
                  </FormItem>
                </Form>

              </Col>

            </Row>
            <div className='tabJj'>
              <Card
                className={styles.colorBackgrounds}
                bordered={false}
              >
                <Spin spinning={this.state.login}>
                  {this.tables()}
                </Spin>
              </Card>
            </div>
            <Row>
              <Drawer
                title={<FormattedMessage id="app.overView.editQa" />}
                placement="right"
                closable
                onClose={this.onClose}
                visible={this.state.close}
                width={800}
                destroyOnClose
              >

                <EditQa questions={this.state.questions} qaId={this.state.qaId} onClose={this.onClose} />
              </Drawer>
            </Row>
          </div>
        </PageHeaderWrapper>
      </div>
    );
  }

  onClose = () => {
    this.setState({
      close: false,
      qaId: '',
      // isUpdate: true
    });
  }

  onChangeA = (a) => { // 页数选择
    this.setState({ page: a, }, () => {
      this.detailCategoryList()
    })
  }

  onShowSizeChangeA = (a, b) => {
    this.setState({ page: a, limit: b, zongsa: b }, () => {
      this.detailCategoryList()
    })
  }

  handleChange = (pagination, filters, sorter) => {
    // this.sort(sorter)
    if (Object.keys(sorter).length == 0) {
      // 未选中
      this.setState({ sort: 'desc', order: 'hitCount' }, () => {
        this.detailCategoryList()
      })
    }
    if (sorter.field === 'hitCount') { // hitCount：命中次数排序
      if (sorter.order === 'ascend') { // 升序
        this.setState({ sort: 'asc', order: 'hitCount' }, () => {
          this.detailCategoryList()
        })
      }
      if (sorter.order === 'descend') { // 降序
        this.setState({ sort: 'desc', order: 'hitCount' }, () => {
          this.detailCategoryList()
        })
      }
    }
    if (sorter.field === 'resolvedCount') { // hitCount：命中次数排序
      if (sorter.order === 'ascend') { // 升序
        this.setState({ sort: 'asc', order: 'resolvedCount' }, () => {
          this.detailCategoryList()
        })
      }
      if (sorter.order === 'descend') { // 降序
        this.setState({ sort: 'desc', order: 'resolvedCount' }, () => {
          this.detailCategoryList()
        })
      }
    }
    if (sorter.field === 'unresolvedCount') { // hitCount：命中次数排序
      if (sorter.order === 'ascend') { // 升序
        this.setState({ sort: 'asc', order: 'unresolvedCount' }, () => {
          this.detailCategoryList()
        })
      }
      if (sorter.order === 'descend') { // 降序
        this.setState({ sort: 'desc', order: 'unresolvedCount' }, () => {
          this.detailCategoryList()
        })
      }
    }
  }

  onChangeB = (a) => { // 页数选择
    this.setState({ page: a, }, () => {
      this.detailDetailList()
    })
  }

  onShowSizeChangeB = (a, b) => {
    this.setState({ page: a, limit: b }, () => {
      this.detailDetailList()
    })
  }

  handleChangeA = (pagination, filters, sorter) => {
    if (Object.keys(sorter).length == 0) {
      // 未选中
      this.setState({ sort: 'desc', order: 'hitCount' }, () => {
        this.detailDetailList()
      })
    }
    if (sorter.field === 'hitCount') { // hitCount：命中次数排序
      if (sorter.order === 'ascend') { // 升序
        this.setState({ sort: 'asc', order: 'hitCount' }, () => {
          this.detailDetailList()
        })
      }
      if (sorter.order === 'descend') { // 降序
        this.setState({ sort: 'desc', order: 'hitCount' }, () => {
          this.detailDetailList()
        })
      }
    }
    if (sorter.field === 'resolvedCount') { // hitCount：命中次数排序
      if (sorter.order === 'ascend') { // 升序
        this.setState({ sort: 'asc', order: 'resolvedCount' }, () => {
          this.detailDetailList()
        })
      }
      if (sorter.order === 'descend') { // 降序
        this.setState({ sort: 'desc', order: 'resolvedCount' }, () => {
          this.detailDetailList()
        })
      }
    }
    if (sorter.field === 'unresolvedCount') { // hitCount：命中次数排序
      if (sorter.order === 'ascend') { // 升序
        this.setState({ sort: 'asc', order: 'unresolvedCount' }, () => {
          this.detailDetailList()
        })
      }
      if (sorter.order === 'descend') { // 降序
        this.setState({ sort: 'desc', order: 'unresolvedCount' }, () => {
          this.detailDetailList()
        })
      }
    }
  }

  export = () => {
    const { sort, from, to, page, limit, search, order, switchPd } = this.state
    const { dispatch } = this.props;
    const data = { from: this.state.beginTime, to: this.state.overTime, order, search, sort }
    if (switchPd === 'a') {
      dispatch({
        type: 'AnswerDetailStatis/exportWD',
        payload: data,
        callback: (res) => {
          // let filename = decodeURIComponent(res.requestRes.headers.get('Content-Disposition').split('=')[1]);
          // download.byBlob(res.fileBlob, filename)
        }
      });
    }
    if (switchPd === 'b') {
      dispatch({
        type: 'AnswerDetailStatis/exportWE',
        payload: data,
        callback: (res) => {
          let filename = decodeURIComponent(res.requestRes.headers.get('Content-Disposition').split('=')[1]);
          download.byBlob(res.fileBlob, filename)
        }
      });
    }
  }
}

export default connect(({ user }) => ({ // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(Answer));
// export default Form.create()(Answer);
